package com.wxh.bomb.httpserver.server;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Date;

/**
 * 封装响应类
 * @className Response
 * @date 2015年12月4日 上午10:42:46
 * @author <a href="mailto:waferslove@sina.com">王星火</a>
 * @version V1.0
 */
public class Response {
	// 响应头信息
	private StringBuilder headInfo;
	// 正文
	private StringBuilder content;
	// 正文长度
	private int len;
	// 输出流
	private BufferedWriter writer;
	
	private static final String CRLF="\r\n";
	private static final String BLANK=" ";
	
	// 构造方法初始化
	private Response() {
		this.headInfo = new StringBuilder();
		this.content = new StringBuilder();
	}
	
	// 构造方法初始化输出流
	public Response(Socket client) {
		this();
		try {
			writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
		} catch (IOException e) {
			headInfo = null;
		}
	}
	
	// 输出
	public Response print(String info){
		if(null != info && !"".equals(info)){
			content.append(info);
			len += info.getBytes().length;
		}
		return this;
	}
	
	// 回车输出
	public Response println(String info){
		if(null != info && !"".equals(info)){
			print(info).content.append(CRLF);
			len += CRLF.getBytes().length; 
		}
		return this;
	}
	
	// 构建响应头信息
	private void createHeadInfo(int code){
		//1)  HTTP协议版本、状态代码、描述
		headInfo.append("HTTP/1.1").append(BLANK).append(code).append(BLANK);
		switch(code){
			case 200:
				headInfo.append("OK");
				break;
			case 404:
				headInfo.append("NOT FOUND");
				break;
			case 505:
				headInfo.append("SEVER ERROR");
				break;	
		}
		headInfo.append(CRLF);
		//2)  响应头(Response Head)
		headInfo.append("Server:bjsxt Server/0.0.1").append(CRLF);
		headInfo.append("Date:").append(new Date()).append(CRLF);
		headInfo.append("Content-type:text/html;charset=GBK").append(CRLF);
		//正文长度 ：字节长度
		headInfo.append("Content-Length:").append(len).append(CRLF);
		headInfo.append(CRLF); //分隔符
	}
	
	// 推送到客户端
	public void pushToClient(int code) throws IOException{
		// 响应初始化失败
		if(null == headInfo){
			code = 500;
		}
		// 设置响应头
		createHeadInfo(code);
		// 输出响应头
		writer.append(headInfo.toString());
		// 输出正文
		writer.append(content.toString());
		writer.flush();
	}
}
